# main.py（主程序入口）
import matplotlib.pyplot as plt
from data_loader import load_data
from genetic_algorithm import EnhancedGeneticAlgorithm


def visualize_solution(solution, instance):
    """可视化解决方案"""
    plt.figure(figsize=(12, 8))

    # 绘制所有客户点
    for c in instance.customers[1:]:
        plt.plot(c.x, c.y, 'bo')
        plt.text(c.x, c.y, f'{c.id}', fontsize=8)

    # 绘制仓库
    depot = instance.depot
    plt.plot(depot.x, depot.y, 'rs', markersize=10)

    # 绘制路径
    current_route = [depot]
    for c_id in solution:
        customer = instance.customers[c_id]
        plt.plot([current_route[-1].x, customer.x],
                 [current_route[-1].y, customer.y], 'g--')
        current_route.append(customer)

    # 返回仓库
    plt.plot([current_route[-1].x, depot.x],
             [current_route[-1].y, depot.y], 'g--')

    plt.title("VRPTW Solution Visualization")
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.grid(True)
    plt.show()


def main():
    # 加载数据
    instance = load_data()

    # 配置算法参数
    ga = EnhancedGeneticAlgorithm(
        instance,
        pop_size=100,
        min_pop_size=50,
        max_generations=200,
        crossover_rate=0.85,
        mutation_rate=0.15,
        T=15
    )

    # 运行算法
    best_solution, history = ga.solve()

    # 输出结果
    print("\n最优路径：")
    print(f"路径顺序: {best_solution}")
    print(f"总成本: {history[-1]:.2f} 分钟")

    # 可视化
    visualize_solution(best_solution, instance)

    # 绘制收敛曲线
    plt.plot(history)
    plt.title("Convergence Curve")
    plt.xlabel("Generation")
    plt.ylabel("Best Cost")
    plt.grid(True)
    plt.show()


if __name__ == "__main__":
    main()